<?php
declare (strict_types=1);

namespace app\controller;

use app\model\ProgressLog as ProgressLogModel;
use app\model\Task as TaskModel;
use think\facade\Request;
use think\facade\Validate;

class ProgressLog
{
    public function logProgress()
    {
        $data = Request::post();

        // 验证数据
        $validate = Validate::rule([
            'task_id' => 'require|integer',
            'progress' => 'require|integer|between:0,100',
            'notes' => 'max:1000'
        ]);

        if (!$validate->check($data)) {
            return json(['error' => $validate->getError()], 400);
        }

        // 检查任务是否存在
        $task = TaskModel::find($data['task_id']);
        if (!$task) {
            return json(['error' => '任务不存在'], 404);
        }

        // 记录进度
        $progressLog = new ProgressLogModel();
        $progressLog->task_id = $data['task_id'];
        $progressLog->user_id = $data['user_id'];  // 从登录状态获取
        $progressLog->progress = $data['progress'];
        $progressLog->notes = $data['notes'];
        $progressLog->save();

        // 更新任务状态为 "进行中" 或 "已完成"
        if ($data['progress'] == 100) {
            $task->status = 'completed';
        } else {
            $task->status = 'in_progress';
        }
        $task->save();

        return json(['message' => '进度记录成功', 'progress_log_id' => $progressLog->log_id]);
    }

    // 更新进度日志
    public function update()
    {
        $data = Request::post();

        $validate = Validate::rule([
            'log_id' => 'require|integer',
            'progress' => 'require|max:500',
            'date' => 'date',
        ]);

        if (!$validate->check($data)) {
            return json(['status' => 'error', 'message' => $validate->getError()]);
        }

        $log = ProgressLogModel::find($data['log_id']);
        if (!$log) {
            return json(['status' => 'error', 'message' => 'Progress log not found']);
        }

        $log->progress = $data['progress'];
        $log->date = $data['date'] ?? $log->date;
        $log->save();

        return json(['status' => 'success', 'message' => 'Progress log updated successfully']);
    }

    // 删除进度日志
    public function delete()
    {
        $data = Request::post();

        $validate = Validate::rule([
            'log_id' => 'require|integer',
        ]);

        if (!$validate->check($data)) {
            return json(['status' => 'error', 'message' => $validate->getError()]);
        }

        $log = ProgressLogModel::find($data['log_id']);
        if (!$log) {
            return json(['status' => 'error', 'message' => 'Progress log not found']);
        }

        $log->delete();

        return json(['status' => 'success', 'message' => 'Progress log deleted successfully']);
    }
}
